class WebSocketService {
	constructor(url) {
		this.url = url
		this.socketTask = null
		this.callbacks = {}
	}

	connect() {
		if (this.socketTask) return
		this.socketTask = uni.connectSocket({
			url: this.url,
			success: () => {
				console.log('WebSocket connecting...')
			}
		})
		this.socketTask.onOpen(() => {
			console.log('WebSocket opened')
		})
		this.socketTask.onMessage((res) => {
			const data = JSON.parse(res.data)
			// 触发对应的回调
			if (data.messageType && this.callbacks[data.messageType]) {
				this.callbacks[data.messageType](data)
			}
		})
		this.socketTask.onClose(() => {
			console.log('WebSocket closed')
			this.socketTask = null
		})
	}

	send(payload) {
		if (this.socketTask) {
			this.socketTask.send({
				data: JSON.stringify(payload),
				complete: (result) => {
					console.log(result)
				}
			})
		}
	}

	on(event, callback) {
		this.callbacks[event] = callback
	}

	close() {
		if (this.socketTask) {
			this.socketTask.close()
			this.socketTask = null
		}
	}
}

export default new WebSocketService('ws://localhost:8080/ws')